using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Book.Blog.Core.Entities;
using Book.Blog.Core.Entities.Settings;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Book.Blog.Infrastructure.Data
{
    public class DatabaseInitializer
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<DatabaseInitializer> _logger;

        public DatabaseInitializer(
            IServiceProvider serviceProvider,
            ILogger<DatabaseInitializer> logger)
        {
            _serviceProvider = serviceProvider;
            _logger = logger;
        }

        public async Task InitializeAsync()
        {
            try
            {
                using var scope = _serviceProvider.CreateScope();
                var context = scope.ServiceProvider.GetRequiredService<BlogDbContext>();
                var userManager = scope.ServiceProvider.GetRequiredService<UserManager<User>>();
                var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole<Guid>>>();

                _logger.LogInformation("开始初始化数据库...");

                // 确保数据库已创建
                await context.Database.EnsureCreatedAsync();

                // 应用迁移
                if (context.Database.GetPendingMigrations().Any())
                {
                    _logger.LogInformation("正在应用数据库迁移...");
                    await context.Database.MigrateAsync();
                }

                // 初始化角色
                await InitializeRolesAsync(roleManager);

                // 初始化管理员用户
                await InitializeAdminUserAsync(userManager);

                // 初始化默认分类
                await InitializeDefaultCategoryAsync(context);

                // 初始化系统设置
                await InitializeSystemSettingsAsync(context);

                _logger.LogInformation("数据库初始化完成。");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化数据库时发生错误");
                throw;
            }
        }

        private async Task InitializeRolesAsync(RoleManager<IdentityRole<Guid>> roleManager)
        {
            _logger.LogInformation("正在初始化角色...");
            var roles = new[] { "Admin", "Editor", "User" };
            foreach (var role in roles)
            {
                if (!await roleManager.RoleExistsAsync(role))
                {
                    _logger.LogInformation($"创建角色: {role}");
                    await roleManager.CreateAsync(new IdentityRole<Guid>(role));
                }
            }
        }

        private async Task InitializeAdminUserAsync(UserManager<User> userManager)
        {
            _logger.LogInformation("正在初始化管理员用户...");
            if (!await userManager.Users.AnyAsync())
            {
                var adminUser = new User
                {
                    UserName = "admin",
                    Email = "admin@example.com",
                    EmailConfirmed = true
                };

                var result = await userManager.CreateAsync(adminUser, "Admin123!");
                if (result.Succeeded)
                {
                    _logger.LogInformation("已创建管理员用户");
                    await userManager.AddToRoleAsync(adminUser, "Admin");
                }
                else
                {
                    _logger.LogWarning("创建管理员用户失败: {Errors}", 
                        string.Join(", ", result.Errors.Select(e => e.Description)));
                }
            }
        }

        private async Task InitializeDefaultCategoryAsync(BlogDbContext context)
        {
            _logger.LogInformation("正在初始化默认分类...");
            if (!await context.Categories.AnyAsync())
            {
                var defaultCategory = new Category
                {
                    Name = "默认分类",
                    Slug = "default",
                    Description = "默认分类",
                    SortOrder = 0
                };
                context.Categories.Add(defaultCategory);
                await context.SaveChangesAsync();
                _logger.LogInformation("已创建默认分类");
            }
        }

        private async Task InitializeSystemSettingsAsync(BlogDbContext context)
        {
            _logger.LogInformation("正在初始化系统设置...");
            if (!await context.Settings.AnyAsync())
            {
                var defaultSettings = new List<SystemSetting>
                {
                    new SystemSetting
                    {
                        Key = "SiteName",
                        Value = "Book Blog",
                        Description = "网站名称",
                        Type = "String",
                        IsPublic = true,
                        Group = "Site",
                        SortOrder = 0
                    },
                    new SystemSetting
                    {
                        Key = "SiteDescription",
                        Value = "一个简单的博客系统",
                        Description = "网站描述",
                        Type = "String",
                        IsPublic = true,
                        Group = "Site",
                        SortOrder = 1
                    }
                };
                context.Settings.AddRange(defaultSettings);
                await context.SaveChangesAsync();
                _logger.LogInformation("已创建默认系统设置");
            }
        }
    }
} 